package com.lzc.tlmail.tlmailproduct.service.impl;

import com.lzc.common.constant.ProductConstant;
import com.lzc.common.to.SkuDiscount;
import com.lzc.common.to.SkuWareVo;
import com.lzc.common.to.SpuBoundsTo;
import com.lzc.common.to.es.SkuEsModel;
import com.lzc.common.utils.R;
import com.lzc.tlmail.tlmailproduct.entity.*;
import com.lzc.tlmail.tlmailproduct.feign.CouponFeignService;
import com.lzc.tlmail.tlmailproduct.feign.SearchFeignService;
import com.lzc.tlmail.tlmailproduct.feign.WareFeignService;
import com.lzc.tlmail.tlmailproduct.service.*;
import com.lzc.tlmail.tlmailproduct.vo.*;
//import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzc.common.utils.PageUtils;
import com.lzc.common.utils.Query;

import com.lzc.tlmail.tlmailproduct.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoService spuInfoService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private ProductAttrValueService attrValueService;

    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private AttrService attrService;
    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存spu信息 好多保存的 就是后台商品发布那里保存 的这里应该用到分布式事务 现在来整合分布式事务
     *
     * @param spuInfovo
     */
//    @GlobalTransactional
    @Transactional
    @Override
    public void savaSpuInfo(SpuInfoVo spuInfovo) {
        //1保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfovo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.spuInfoService.saveSpuInfo(spuInfoEntity);
        //2保存spu图片 pms_spu_images

        List<String> images = spuInfovo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), images);

        //3保存描述  pms_spu_info_desc
        List<String> decript = spuInfovo.getDecript();
        spuInfoDescService.saveSpuDecs(spuInfoEntity.getId(), decript);
        //4保存 积分sku tlmail_sms 库 sms_spu_bounds
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        Bounds bounds = spuInfovo.getBounds();
        BeanUtils.copyProperties(bounds, spuBoundsTo);
        spuBoundsTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundsTo);
        if (r.getCode() != 0) {
            log.error("远程调用保存spu积分失败");
        }
        //5保存基本规格参数 pms_product_attr_value
        attrValueService.saveAttrValue(spuInfovo.getBaseAttrs(), spuInfoEntity.getId());
        //6保存sku
        List<Skus> skus = spuInfovo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(sku -> {
                // 6.1基本sku pms_sku_info
                List<Images> images1 = sku.getImages();
                String defaultImg = "";
                //得到默认图片
                if (images1 != null && images.size() > 0) {
                    for (Images item : images1) {
                        if (item.getDefaultImg() == 1) {
                            defaultImg = item.getImgUrl();
                        }
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDesc(String.join(",", sku.getDescar()));
                skuInfoService.save(skuInfoEntity);
                Long skuId = skuInfoEntity.getSkuId();
                //6.2 sku图片 pms_sku_images
                List<SkuImagesEntity> skuImagesEntities = sku.getImages().stream().map(images2 -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(images2.getImgUrl());
                    skuImagesEntity.setDefaultImg(images2.getDefaultImg());
//                    skuImagesEntity.setImgSort(skuImagesEntity.getImgSort());
                    return skuImagesEntity;
                }).filter(entity -> {
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntities);
                //6.3 sku销售属性 pms_sku_sale_attr_value
                List<Attr> attr = sku.getAttr();
                if (attr != null && attr.size() > 0) {
                    List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(attr1 -> {
                        SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                        BeanUtils.copyProperties(attr1, skuSaleAttrValueEntity);
                        skuSaleAttrValueEntity.setSkuId(skuId);
                        return skuSaleAttrValueEntity;
                    }).collect(Collectors.toList());
                    skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
                }
                // 6.4 sku tlmail_sms库满减sms_sku_full_reduction表   满几件打几折sms_sku_ladder 会员折扣sms_member_price
                SkuDiscount skuDiscount = new SkuDiscount();
                BeanUtils.copyProperties(sku, skuDiscount);
                // List<MemberPrice> memberPrice = sku.getMemberPrice();
//                List<MemberPrice> memberPriceTos = memberPrice.stream().map(memberPrice1 -> {
//                    MemberPrice memberPriceTo = new MemberPrice();
//                    BeanUtils.copyProperties(memberPrice1, memberPriceTo);
//                    return memberPriceTo;
//                }).collect(Collectors.toList());
//                skuDiscount.setMemberPrice(memberPriceTos);
                skuDiscount.setSkuId(skuId);
                if (skuDiscount.getFullCount() > 0 || skuDiscount.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                    R r1 = couponFeignService.saveSkuDiscount(skuDiscount);
                    if (r1.getCode() != 0) {
                        log.error("远程调用保存优惠信息失败");
                    }
                }

            });

        }
    }


    /**
     * 添加spu基本信息
     *
     * @param spuInfoEntity
     */
    @Override
    public void saveSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.getBaseMapper().insert(spuInfoEntity);
    }

    /**
     * 检索spu信息
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByConditoon(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if(key!=null){
            queryWrapper.and(w->{
                w.eq("id",key).or().eq("spu_name",key);
            });
        }
        Long brandId = (Long) params.get("brandId");
        if(brandId!=null&&brandId!=0){
            queryWrapper.eq("brand_id",brandId);
        }
        Long catelogId = (Long) params.get("catelogId");
        if(catelogId!=null&&catelogId!=0){
            queryWrapper.eq("catalog_id",catelogId);
        }
        Long status = (Long) params.get("status");
        if(status!=null){
            queryWrapper.eq("publish_status",status);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 商品上架功能
     * @param spuId
     */
    @Override
    public void up(Long spuId) {
        /**
         * 从数据库读取数据放到es中
         */
        //1组装数据

        //1查出当前spuid查询所有的sku信息
        List<SkuInfoEntity> skuInfoEntities=skuInfoService.querySkuBySpuId(spuId);
        List<Long> skuIdList = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        //TODO 4 查询当前sku规格属性 查出可以被检索的
        List<ProductAttrValueEntity> attrValueEntities = attrValueService.getAttrBySpuId(spuId);
        List<Long> longs = attrValueEntities.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        //得到可以被检索的属性id
        List<Long> searchAttrIdS=attrService.selectSearchAttrs(longs);
        //过滤得到可以检索的属性 这里没转成set装 看看会不会报错
        //Set<Long> idSet = new HashSet<>(searchAttrIdS);
        List<SkuEsModel.Attrs> attrsList = attrValueEntities.stream().filter(attrvalue -> {
            return searchAttrIdS.contains(attrvalue.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs1);
            return attrs1;
        }).collect(Collectors.toList());

        //TODO 1 发送远程调用库存系统查询是否有库存
        Map<Long, Boolean> stockMap=null;
        try {
            List<SkuWareVo> skusHasStock = wareFeignService.getSkusHasStock(skuIdList);
            stockMap = skusHasStock.stream().collect(Collectors.toMap(SkuWareVo::getSkuId, item -> item.getHasStock()));
        }catch (Exception e){
            log.error("库存服务查询异常 远程调用失败");
            e.printStackTrace();
        }

        //传数据
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> skuEsModels = skuInfoEntities.stream().map(skuInfoEntity -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(skuInfoEntity, skuEsModel);
            skuEsModel.setSkuPrice(skuInfoEntity.getPrice());
            skuEsModel.setSkuImg(skuEsModel.getSkuImg());
            //设置库存信息
            if(finalStockMap ==null){
                skuEsModel.setHasStock(true);
            }else {
                skuEsModel.setHasStock(finalStockMap.get(skuInfoEntity.getSkuId()));
            }
            //TODO 2 热度评分 0
            skuEsModel.setHotScore(0L);
            //TODO 3 查询品牌和分类的名字信息

            BrandEntity brandEntity = brandService.getById(skuEsModel.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            CategoryEntity categoryEntity = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());
            //设置检索属性
            skuEsModel.setAttrs(attrsList);
            return skuEsModel;
        }).collect(Collectors.toList());

        //TODO 5将数据发送给ES保存
        R r = searchFeignService.productUp(skuEsModels);
        if(r.getCode()==0){
            //远程调用成功
            //todo spu发布状态修改
            this.baseMapper.updateStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else {
            //远程调用失败
            //todo 7 接口幂等性
            /**
             * 1 构造请求数据 将对象转为json
             * 2 发送请求进行执行
             */
        }
    }

    /**
     * 根据skuid得到spu信息
     * @param skuid
     * @return
     */
    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuid) {
        SkuInfoEntity byId = skuInfoService.getById(skuid);
        SpuInfoEntity spuInfoEntity = this.getById(byId.getSpuId());
        return spuInfoEntity;
    }

}